package com.dsaa.code2_tree;

import com.alibaba.fastjson.JSON;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class Codec {

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        return reserialize(root, "");
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        String[] dataArray = data.split(",");
        List<String> dataList = new LinkedList<>(Arrays.asList(dataArray));
        return rdeserialize(dataList);
    }

    public String reserialize(TreeNode root, String str) {
        if (root == null || root.val == null) {
            str += "null,";
        } else {
            str += root.val + ",";
            str = reserialize(root.left, str);
            str = reserialize(root.right, str);
        }
        return str;
    }

    public TreeNode rdeserialize(List<String> dataList) {
        if ("null".equals(dataList.get(0)) || "".equals(dataList.get(0))) {
            dataList.remove(0);
            return null;
        }

        TreeNode root = new TreeNode(Integer.valueOf(dataList.get(0)));
        dataList.remove(0);

        root.left = rdeserialize(dataList);
        root.right = rdeserialize(dataList);

        return root;
    }


    public static void main(String[] args) {
        Codec ser = new Codec();
        Codec deser = new Codec();
        TreeNode root = TreeNode.deserialize("1, 2, 3, null, null, 4, 5");
        String serialize = ser.serialize(root);
        System.out.println(serialize);
        TreeNode ans = deser.deserialize(serialize);
        System.out.println(JSON.toJSONString(TreeNode.serialize(ans)));
    }
}

// Your Codec object will be instantiated and called as such:
// Codec ser = new Codec();
// Codec deser = new Codec();
// TreeNode ans = deser.deserialize(ser.serialize(root));